import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '../store/index';
Vue.use(VueRouter);
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  undefined;
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch((err) => err);
};
const routes = [
  { path: '/', component: () => import('../views/index.vue') },
  {
    path: '/login',
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/user/:user_id',
    name: 'user',
    component: () => import('../views/User.vue'),
  },
  {
    path: '/admin',
    name: 'admin',
    component: () => import('../views/admin/index.vue'),
    beforeEnter: (to, from, next) => {
      if (store.state.user_level == 7) {
        next();
      } else {
        next(false);
        alert('只有管理员可以进入');
      }
    },
    children: [
      {
        path: '/',
        redirect: 'welcome',
      },
      {
        path: 'welcome',
        component: () => import('../views/admin/Welcome.vue'),
      },
      {
        name: 'topicManager',
        path: 'topic',
        component: () => import('../views/admin/Topics.vue'),
      },
      {
        name: 'userManager',
        path: 'user',
        component: () => import('../views/admin/Users.vue'),
      },
      {
        name: 'typeManager',
        path: 'type',
        component: () => import('../views/admin/Types.vue'),
      },
    ],
  },
  {
    path: '/edit',
    name: 'edit',
    component: () => import('../views/EditUser.vue'),
    beforeEnter: (to, from, next) => {
      if (
        sessionStorage.getItem('authorization') !== '' &&
        sessionStorage.getItem('authorization') != undefined
      ) {
        next();
      } else {
        next('/login');
      }
    },
  },
  {
    path: '/article/:topic_id',
    name: 'article',
    component: () => import('../views/Article.vue'),
    beforeEnter: (to, from, next) => {
      if (to.params.topic_id != '' && to.params.topic_id) {
        next();
      } else {
        next('/');
      }
    },
  },
  {
    path: '/create',
    name: 'create',
    component: () => import('../views/Create.vue'),
    beforeEnter: (to, from, next) => {
      if (
        sessionStorage.getItem('authorization') !== '' &&
        sessionStorage.getItem('authorization') != undefined
      ) {
        next();
      } else {
        next('/login');
      }
    },
  },
  {
    path: '*',
    redirect: '/',
  },
];

const Router = new VueRouter({
  routes,
});

Router.beforeEach(async (to, from, next) => {
  if (sessionStorage.getItem('authorization')) {
    await store.dispatch('getUserInfo');
    next();
  } else {
    next();
  }
});
export default Router;
